<?php

namespace App\Http\Controllers\OgreenCard;

use App\Service\ExcelExport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use App\Service\ExcelImport;


class OrderController extends BaseController
{
    public function orders(Request $i){

        $beginDate  = trim($i->input('beginDate'));
        $endDate    = trim($i->input("endDate"));
        $exBeginDate= trim($i->input('exBeginDate',''));
        $exEndDate  = trim($i->input('exEndDate',''));
        $id         = trim($i->input('id',0));
        $user = trim($i->input('user'));
        $manager=trim($i->input('manager'));
        $bankManager = trim($i->input('bankManager',""));
        $cardType = $i->input('cardType',"");
        $export    = $i->input("export",'');

        $orders = DB::table('og_order as a')
            ->leftJoin("og_admin as d","d.id",'=','a.manager')
            ->where('a.com_id',COM_ID);

        if($bankManager) {
            $orders->where(function($db) use ($bankManager) {
                $bankManager = "%".$bankManager."%";
                $db->where('a.bank_manager',"like", $bankManager)->orWhere('a.bank','like',$bankManager);
            });
        }
        if($manager) $orders->where("a.manager",$manager);
        if($beginDate) $orders->where("a.created_at",">=",$beginDate." 00:00:01");
        if($endDate) $orders->where("a.created_at","<=",$endDate." 23:59:59");
        if($cardType) $orders->where("a.card_type",$cardType);
        if($exBeginDate) $orders->where('exchange_at','>=',$exBeginDate.' 00:00:00');
        if($exEndDate) $orders->where('exchange_at',"<=",$exEndDate.' 23:59:59');
        if($id>0)   $orders->where('order_id',$id);
        if($user){
            $orders->where(function($db)use($user)
            {
                $user = "%".$user."%";
                $db->where("user_name","like",$user)
                    ->orWhere("user_mobile","like",$user)
                    ->orWhere("express_user","like",$user)
                    ->orWhere("express_code","like",$user);
            });
        }
        $admin = $i->session()->get("manager");
        if($admin->role == ROLE_SALE){
            $orders->where("manager",$admin->id);
        }
        $orders = $orders->select("a.*",'d.real_name as saler')->orderBy("order_id","desc");
        if($export){
            $orders = $orders->get();
        } else{
            $orders = $orders->paginate();
        }

        $oTypes = self::$orderTypes;
        $cardTypes = self::$orderCardTypes;
        foreach($orders as $order)
        {
            $orderGoods = DB::table("og_order_pack as a")
                ->leftJoin("og_pack as b","b.pack_id","=","a.pack_id")
                ->where('a.order_id',$order->order_id)
                ->select("a.*","b.pack_name","b.pack_money")
                ->get();


            if($order->card_id){

                $cards = DB::table("og_card")->whereIn('card_id',explode(",",$order->card_id))->select("code","pwd")->get();

            }else{
                $cards = [];
            }
            $order->type_name = $oTypes[$order->type];
            $order->card_type = $cardTypes[$order->card_type];
            $order->cards = $cards;
            $order->goods = $orderGoods;
        }


        //return $this->order_export($orders);
        if($export){
            return $this->order_export($orders);
        }

        $adminInfo = $i->session()->get("manager");
        $managers = DB::table("og_admin");
        if($adminInfo->role == 2)
        {
            $managers->where("id",$adminInfo->id); //销售员只能看自己的
        }
        $managers = $managers->where('com_id',COM_ID)->get();


        $params = [
            'user'=>$user,
            'beginDate'=>$beginDate,
            "endDate"=>$endDate,
            'exBeginDate'=>$exBeginDate,
            'exEndDate'=> $exEndDate,
            "bankManager"=>$bankManager,
            "manager"   => $manager,
            "cardType"=>$cardType,
        ];
        $status = ["已完成","未完成"];
        $data = [
            'orders'=>$orders,
            'status'=>$status,
            "types"=>$cardTypes,
            'params'=>$params,
            'managers'=>$managers
        ];
        return self::view("order.order-list",$data);
    }

    public function order_export($orders){
        $exportData = [
            ["订单编号","订单类型","客户姓名","联系方式","销售","支行","理财经理","收件姓名","收货电话","收件地址","物流单号",
                "总积分","卡号","密码","产品","积分","面值","数量","单品备注",'订单备注','兑换日期','下单时间']
        ];
        foreach($orders as $o)
        {

            if(count($o->cards) > 0){
                $cards = $o->cards;

            }else{

                $cards = [['code'=>$o->pos_code,'pwd'=>'']];
                $cards = json_decode(json_encode($cards));
            }
            $numCards = count($cards);
            $numGoods = count($o->goods);
            $loopNum  = max($numGoods,$numCards);

            $base = [
                $o->order_id,
                $o->card_type,
                $o->user_name,
                $o->user_mobile,
                $o->saler,
                $o->bank,
                $o->bank_manager,
                $o->express_user,
                $o->express_mobile,
                $o->express_address,
                $o->express_code,
                $o->total_price,
                '',//产品，卡券信息插入到这里
                $o->note,
                //substr($o->exchange_at,0,10),
                $o->exchange_at ? date("Y年m月d日",strtotime($o->exchange_at)): '',
                substr($o->created_at,0,10),
            ];

            $goods = $o->goods;
            for($i=0;$i<$loopNum;$i++){

                if(isset($cards[$i])){
                    $code = $cards[$i]->code;
                    $pwd = $cards[$i]->pwd;
                }else{
                    $code = '';
                    $pwd = '';
                }

                if($i==1){
                    $base = array_fill(0,count($base)-2,'');
                    $base[] = $o->exchange_at ? date("Y年m月d日",strtotime($o->exchange_at)): '';
                    $base[] = substr($o->created_at,0,10);
                }

                if(isset($goods[$i])){
                    $g = $goods[$i];
                    $packName = $g->pack_name;
                    $price = $g->price;
                    $money = $g->pack_money;
                    $num = $g->num;
                    $note = $g->note;
                }else{
                    $packName = '';
                    $price = '';
                    $money = '';
                    $num = '';
                    $note = '';
                }

                $gInfo = [
                    $code,
                    $pwd,
                    $packName,
                    $price,
                    $money,
                    $num,
                    $note,
                ];

                $row = $base;
                array_splice($row,12,1,$gInfo);
                $exportData[] = $row;
            }
        }

        $export = new ExcelExport($exportData);
        return Excel::download($export, "中行积分订单".date('YmdHi').'.xlsx');
    }

    public function orderDel(){

    }

    public function orderCard(Request $i)
    {
        if($i->method() == "GET")
        {
            return self::view("order.order-card");
        }

        /*批量添加卡号*/
        if($i->hasFile("excel"))
        {
            $cards = Excel::toArray(new ExcelImport,$i->file('excel'));
            $cards = $cards[0];
            $title = array_splice($cards,0,1);
            $newCards = [];
            foreach($cards as $c){
                $newCards[] = ["code"=>$c[0],"pwd"=>$c[1]];
            }
            $cards = $this->check_card($newCards);
            return self::response(["cards"=>$cards]);
        }


        /*将信息缓存
        1.订单类型
        2.总积分
        3.交易流水
        4.卡号
        */
        $orderType = $i->input('orderType');
        $totalPrice = $i->input('totalPrice',0);
        $tradeCode = $i->input('tradeCode',"");
        /*检查总积分数量*/
        if(($orderType == 'pos' || $orderType == 'sg') && $totalPrice <=0){
            return self::response("积分必须大于0");
        }

        if($orderType == 'pos' && $tradeCode == ""){
            return self::response("POS机订单必须添加流水号");
        }

        /*检查卡券*/
        $cards = [];
        if($orderType == 'wx'){

            //过滤掉无用的字段
            $codes = $i->input('code');
            $pwd   = $i->input('pwd');

            foreach($codes as $key=> $code){
                if($code == "" && $pwd[$key] == ""){
                    continue;
                }

                if(!($code && $pwd[$key]))
                {
                    return self::response("【".$code."@".$pwd[$key]."】卡号和密码必须齐全");
                }
                $cards[] = ["code"=>$code,"pwd"=>$pwd[$key]];
            }

            $cards = $this->check_card($cards);
            $totalPrice = 0;
            foreach($cards as $card){
                if($card['valid'] == 0)
                {
                    return self::response("[".$card['code'].'@'.$card['pwd']."]".$card["msg"]);
                }

                $totalPrice += $card['price'];
            }
        }
        $storage = [
            "tradeCode"=>$tradeCode,
            "totalPrice"=>$totalPrice,
            "orderType"=>$orderType,
            "cards"=>$cards
        ];

        $i->session()->put("order",$storage);
        return self::response();
    }

    public function check_card(array $cards){
        foreach($cards as &$card)
        {
            $card['com_id'] = COM_ID;
            $card['code'] = strtoupper($card['code']);
            $card['pwd'] = strtoupper($card['pwd']);

            $has = DB::table('og_card')->where(['code'=>$card['code'],'pwd'=>$card['pwd'],'com_id'=>COM_ID])->first();
            $card['price'] = 0;
            $card['msg'] = "";

            if(!$has){
                $card['valid'] = 0;
                $card['msg'] = "卡券不存在";
                continue;
            }
            if($has->used_at) {
                $card['valid'] = 0;
                $card['msg'] = "卡券已使用";
                continue;
            }

            if($has->deleted_at){
                $card['valid'] = 0;
                $card['msg'] = "卡券已作废";
                continue;
            }
            $card['id'] = $has->card_id;
            $card['valid'] = 1;
            $card['msg'] = "卡券有效";
            $card['price'] = $has->price;
        }

        return $cards;
    }

    public function orderEdit(Request $i)
    {
        $id = $i->input('id',0);

        if($id > 0){

            $order = DB::table("og_order")->where('order_id',$id)->first();
            $goods = DB::table("og_pack as a")
                ->leftJoin("og_order_pack as b",'b.pack_id','=',DB::raw('a.pack_id  and b.order_id='.$id))
                ->select("a.*","b.num","b.note",'b.og_id')
                ->whereNull('a.deleted_at')
                ->orderBy('a.pack_name')
                ->where('a.com_id',COM_ID)
                ->get();
        }else{

            $sessionOrder = $i->session()->get("order");

            $goods = DB::table("og_pack")->where("com_id",COM_ID)
                ->whereNull("deleted_at")
                ->select("*",DB::raw("1 as num,'' as note,0 as og_id"))
                ->orderBy('pack_name')
                ->get();

            $colums = "order_id,user_name,user_mobile,express_user,express_address,express_date,express_code,".
                "express_mobile,card_code,card_pwd,bank_manager,bank,manager,managerId,note";
            $colums = self::get_empty_arr($colums);
            $colums['orderType'] = $sessionOrder['orderType'];
            $colums['total_price'] = $sessionOrder['totalPrice'];
            $colums["exchange_at"] = date('Y-m-d');
            $colums["card_type"] = "sc";
            $order = (object)$colums;
        }



        $admin = $i->session()->get("manager");
        $managers = DB::table("og_admin")->where("com_id",COM_ID)->whereNull("deleted_at");
        if($admin->role != 1){
            $managers->where("id",$admin->id);
        }

        $managers = $managers->get();
        $orderCardTypes = self::$orderCardTypes;
        $data = [
            'order'=>$order,
            "goods"=>$goods,
            'orderCardTypes'=>$orderCardTypes,
            'managers'=>$managers
        ];

        return self::view("order.order-edit",$data);
    }

    public function orderGoods(Request $i){
        $cardTypes = DB::table("og_pack")
            ->where('com_id',COM_ID)
            ->get();
        return self::view("order.order-goods",["cardTypes"=>$cardTypes]);
    }

    public function orderEditPost(Request $i)
    {

        $data = $i->except(["_token","order_id","gCheck","gId","gNote","gNum"]);
        $orderId = $i->input("order_id");
        $gCheck = $i->input('gCheck');  //已经选择的产品，这几个都是数组，根据是否选中和选中的哪个来决定已选择的产品
        $gId = $i->input("gId");
        $gNote = $i->input("gNote");
        $gNum = $i->input("gNum");

        $goods = [];
        if($gCheck)
        {
            foreach($gCheck as $key => $id)
            {
                $id = (int)$id;
                $goods[] = [
                    "pack_id" => $gId[$id],
                    "num"   => $gNum[$id],
                    "note"  => $gNote[$id]
                ];
            }
        }

        if(count($goods) == 0) return self::response("请选择套餐且数量不能为0");

        $data['updated_at'] = now();

        if($orderId > 0){
            $orderInfo = DB::table("og_order")->where('order_id',$orderId)->first();
            $data['total_price'] = $orderInfo->total_price;
            $data['order_id'] = $orderId;
        }else{
            $data['order_id'] = 0;
            $sessionOrder = $i->session()->get("order");
            $totalPrice = $sessionOrder["totalPrice"];
            $data['total_price'] = $totalPrice;
        }

        $cards = [];
        /*修改订单*/
        if($orderId <= 0){

            /*新增订单*/
            $orderType = $sessionOrder["orderType"];
            $data['type'] = $orderType;

            /*微信订单*/
            if($orderType == 'wx'){
                $cards = $sessionOrder['cards'];
            }elseif($orderType == 'pos'){
                $data['pos_code'] = $sessionOrder['tradeCode'];
            }
        }

        $res = $this->addOrderAction($data,$goods,$cards);
        $i->session()->forget("order");
        return self::send();
    }

    public function addOrderAction(array $orderInfo,array $goods,array $cards=[])
    {
        $data = $orderInfo;
        $orderId = $orderInfo["order_id"];

        if(count($goods) == 0) return false;

        $db = DB::table("og_order");
        $data['updated_at'] = now();

        /*检查积分是否足够*/
        $sumPrice = 0;
        if(count($goods) ==0) return "产品为空";

        foreach($goods as &$g)
        {
            $info = DB::table("og_pack")->where("pack_id",$g['pack_id'])->select('pack_price')->first();
            $g['price'] = $info->pack_price;
            $sumPrice += $g['price'] * $g['num'];
        }

        if($sumPrice > $data["total_price"]) return "积分不足";

        /*修改订单*/
        if($orderId > 0)
        {
            $db->where('order_id',$orderId)->update($data);
            //删除历史商品信息
            DB::table("og_order_pack")->where('order_id',$orderId)->delete();

        }else {

            /*新增订单*/
            $orderType = $data["type"];
            $data['created_at'] = now();
            $data['type'] = $orderType;

            /*微信订单*/
            if(count($cards) > 0){
                $cids = [];
                $cards = $this->check_card($cards);
                foreach($cards as $c)
                {
                    if($c["valid"] ==0)
                    {
                        return $c['code'].'@'.$c['pwd'].$c["msg"];
                    }
                    $cids[] = $c["id"];
                }
                $data['card_id'] = implode(",",$cids);
            }

            $data['com_id'] = COM_ID;
            $orderId = $db->insertGetId($data);

            /*销卡*/
            if(count($cards) > 0)
            {
                DB::table("og_card")->whereIn('card_id',$cids)->update(['used_at'=>now(),'order_id'=>$orderId]);
            }
        }

        /*更新产品*/
        foreach($goods as &$g)
        {
            $g['order_id'] = $orderId;
            DB::table("og_order_pack")->insert($g);
        }

        return true;
    }
    public function orderExpress(Request $i)
    {
        if($i->method() == 'GET'){

            $id = $i->input('id');
            $order = DB::table("og_order")->where('order_id',$id)->first();
            return self::view("order.order-express",['order'=>$order]);
        }

        DB::table("og_order")->where("order_id",$i->input('order_id'))->update($i->except("_token"));

        return self::response();
    }

    private static function my_date($num){
        return gmdate('Y/m/d', ($num - 25569) * 86400);
    }

    public function check_manager_exists($name){
        $manager = DB::table('og_admin')
            ->where('real_name',$name)
            ->where('com_id',COM_ID)
            ->whereNull('deleted_at')
            ->first();
        return $manager ? $manager->id : 0;
    }
    /*订单导入*/
    public function orderImport(Request $i)
    {
        if($i->method() == 'GET')
        {
            return self::view("order.order-import",['orders'=>[],'goods'=>[],'hasError'=>false]);
        }

        if($i->files->has("excel"))
        {
            $excels = Excel::toArray(new ExcelImport,$i->file('excel'));
            $rows = $excels[0];
            $keys = ["name","mobile","bank","bank_manager","manager","date","type","card_type","price",
                "express_user","express_mobile","express_address","express_date","express_company","express_code",
                "code",'pwd','pos_code','note'];

            $orders = [];
            foreach($rows as $row)
            {
                $orders[] = array_combine($keys,$row);
            }

            array_splice($orders,0,1); //去掉标题

            //将多个订单合并成一个订单
            $newOrders = [];
            $nth = -1;
            foreach($orders as $order){

                if($order['name']) { //一个新订单
                    $order['cards'] = [];
                    $newOrders[] = $order;
                    $nth += 1;
                }

                if($order['code']){

                    $newOrders[$nth]['cards'][] = $order['code'].'@'.$order['pwd'];
                }else{
                    $newOrders[$nth]['cards'][] = $order['pos_code'];
                }
            }

            foreach($newOrders as $key => $order){
                unset($order['pwd']);
                unset($order['code']);
                unset($order['pos_code']);
                $order['cards'] = implode("\n",$order['cards']);
                $newOrders[$key] = $order;
            }
            $orders = $newOrders;
            $hasError = false;
            //检测是什么订单，如果有卡券，进行卡券验证

            $uniqueCard = [];
            foreach($orders as $okey => $o)
            {
                if(implode("",$o) == ""){
                    unset($orders[$okey]);
                    continue;
                }
                $orders[$okey]['date'] = $o['date']?self::my_date($o['date']) :'';
                $orders[$okey]['express_date'] = $o['express_date'] ? self::my_date($o['express_date']) : '';
                $orders[$okey]["goods"] = "";

                $cards = $this->parseStrCards($o['cards']);
                $error = "";
                if(count($cards) > 0)
                {
                    $orders[$okey]['price'] = 0;
                    /*进行卡券有效性检查*/
                    $cards = $this->check_card($cards);

                    foreach($cards as $card)
                    {
                        $codePwd = $card['code'].$card['pwd'];
                        if(in_array($codePwd,$uniqueCard)){
                            $error .= "卡号【{$card['code']}@{$card['pwd']}】重复<br/>";
                            $hasError = true;
                        }
                        $uniqueCard[] = $codePwd;

                        if($card['valid'] == 1)
                        {
                            $orders[$okey]['price'] += $card['price'];
                        }else{
                            $error .= $card['code']."@".$card['pwd'].$card["msg"]."<br/>";
                            $hasError = true;
                        }
                    }
                }elseif((int)$o["price"] < 0){
                    $error = "订单金额为0";
                    $hasError = true;
                }

                if(empty($o['type'])){
                    $error = "刷分类型为空";
                    $hasError = true;
                }

                if(empty($o['card_type'])){
                    $error = "订单类型为空";
                    $hasError = true;
                }
                //检查销售是否存在
                if($error== '' && $this->check_manager_exists($o['manager']) == 0){
                    $error = "系统不存在销售".$o['manager'];
                    $hasError = true;
                }
                $orders[$okey]["msg"] = $error;
            }

            $goods = DB::table("og_pack")->whereNull("deleted_at")->where('com_id',COM_ID)->orderBy('pack_name')->get();
            return self::view("order.order-import",["orders"=>$orders,'goods'=>$goods,'hasError'=>$hasError]);
        }


        $orders = $i->input('orders');
        DB::beginTransaction(); //开启事务

        foreach($orders as $order){
            $goods = $order['goods'];
            $cards = $order['cards'];
            $cards = $this->parseStrCards($cards);
            $nGoods = [];
            foreach($goods as $g){
                $nGoods[] = [
                    "pack_id"=>$g['id'],
                    "num"=>$g['num'],
                    "note"=>$g["note"]
                ];
            }

            switch (trim($order['type'])){
                case '手工':$orderType = 'sg';break;
                case 'POS机':$orderType = 'pos';break;
                case '微信':$orderType = 'wx';break;
                default: $orderType = 'sg';
            }

            switch(trim($order['card_type'])){
                case "购物卡":$cardType = "gwk";break;
                case "食材卡":$cardType = "sc";break;
                case "POS机":$cardType = "pos";break;
                case '拍照服务':$cardType = 'ps';break;
                default:$cardType = "";
            }


            if(!$cardType){
                return self::response("不存在【".$order['card_type']."】这种订单类型");
            }

            $nOrder =[
                'user_name' => $order["name"],
                'user_mobile' => $order["mobile"],
                "bank_manager" => $order["bank_manager"],
                "note"  => $order['note'],
                "exchange_at" => $order['date'],
                "total_price" => $order["price"],
                "bank"  => $order['bank'],
                "card_type" => $cardType,
                "type"  => $orderType,
                "order_id" => 0,
                "pos_code" => (count($cards) == 0 && $order['cards']) ? $order['cards']:'',
                "manager"=>$this->check_manager_exists($order['manager']),
                'express_user' => $order['express_user'],
                'express_mobile' => $order['express_mobile'],
                'express_date' => $order['express_date'],
                'express_address' => $order['express_address'],
                'express_code'  => $order['express_code'],
                'express_company' => $order['express_company']
            ];
            $res = $this->addOrderAction($nOrder,$nGoods,$cards);
            if($res === true){

            }else{
                DB::rollback();  //回滚
                return self::response($res);
            }
        }
        DB::commit();  //提交
        return self::response();
    }

    public function parseStrCards($str){
        if(preg_match("/@/",$str))
        {
            $cards = explode("\n",$str);
            foreach($cards as $key => $card)
            {
                $card = explode("@",$card);
                $cards[$key] = ["code"=>trim($card[0],"'"),"pwd"=>trim($card[1],"'")];
            }
            return $cards;
        }else{
            return [];
        }
    }
}
